const vscode = require('vscode');
const fs = require('fs');
const path = require('path');

const COMM = 'vscode-quoteSource-extension'

// 注册命令
const registerCommand = (name, fn, context) => {
  const comd = vscode.commands.registerCommand(`${COMM}.${name}`, fn)
  context.subscriptions.push(comd)
} 

// 弹出提示信息
const message = vscode.window.showInformationMessage;
// 弹出错误提示
const messageErr = vscode.window.showErrorMessage

// 获取当前激活文件的路径和文件名
const getFileBaseInfo = () => {
  const editor = vscode.window.activeTextEditor;
  if (editor) {
    // 获取当前打开文件的完整路径
    const filePath = editor.document.uri.fsPath;
    // 文件名 -- 带后缀
    const orignFileName = path.basename(filePath);
    // 文件名 -- 不带后缀
    const fileName = orignFileName.replace(/^(\S+)\.[a-zA-Z]+$/, '$1');
    // 文件名 -- 首字母大写
    const upperCaseFileName = `${fileName[0].toUpperCase()}${fileName.slice(1)}`

    return { filePath, orignFileName, fileName, upperCaseFileName }
  }
  vscode.window.showInformationMessage('No active editor');
}

// 更改当前组件的name
const fillComponentName = (fileText) => {
  // 分解文件内容
  const reg = /(.+defineComponent\({[\s\S]*?name\s*:\s*['"])(.*)(['"][\s\S]*?setup\s*\(.+)/;
  if (reg.test(fileText)) {
    const { upperCaseFileName } = getFileBaseInfo();
    // 替换
    fileText = fileText.replace(reg, '$1'+ upperCaseFileName + '$3');
  }
  return fileText;
}

// 获取hook使用模板文件
const getHookUseFiel = async (context, hookFileName) => {
	const editor = vscode.window.activeTextEditor;
	if (!editor) return vscode.window.showErrorMessage('No active editor found!');

	const hookFilePath = path.join(context.extensionPath, `/src/hook/${hookFileName}`);
	const fileText = fs.readFileSync(hookFilePath, {encoding: 'utf-8'})
	if (fileText) return fileText
}

// 常用组件集合
const componentMap = {
  Icon: `import { Icon } from '@/components/Icon'`,
  NoDataIcon: `import { NoDataIcon } from '@/components/NoData'`
}
// 插入常用组件
const insertComponent = (componentName) => {
  const editor = vscode.window.activeTextEditor;
  if (componentMap[componentName] && editor) {
    const content = `${componentMap[componentName]}\n\t const Render${componentName} = () => <${componentName} />`

    // 获取当前光标位置
    const position = editor.selection.active;
    editor.edit((editBuilder) => editBuilder.insert(position, content))
  }
}

module.exports = {
  registerCommand,
  getFileBaseInfo,
  getHookUseFiel,
  message,
  messageErr,
  fillComponentName,
  insertComponent
}